import { createContext, useContext, useMemo, useState } from "react"
import { Route, useHistory, useLocation } from "react-router"
import { NavLink } from "react-router-dom"
import { Redirect, Switch } from "react-router-dom/cjs/react-router-dom.min"

const api={
    login(){
        return fetch('https://randomuser.me/api')
        .then(resp=>resp.json())
        .then(json=>json.results[0].login)
    },
    logout(){
        return new Promise(resolve=>setTimeout(resolve,100))
    }
}

const UserContext=createContext()
const UserContextProvider=({children})=>{
    const [user,setUser]=useState(null)
    const contextValue=useMemo(()=>({user,setUser}),[user])

    return <UserContext.Provider value={contextValue}>
        {children}
    </UserContext.Provider>
}

const useUserContext=()=>useContext(UserContext)

const Public=()=>{
    return <>
    <h2>公共页面</h2>
    </>
}
const Login=()=>{
    const {setUser}=useUserContext()
    const location=useLocation()
    const history=useHistory()
    return <>
    <h2>登录</h2>
    <button onClick={() => {
        api.login().then(user => {
          setUser(user)
          history.push(
            location?.state?.from || '/auth/pub'
          )
        })
      }}>登录</button>
    </>
}

const MyPage2=()=>{
    return(
        <h2>我的第二个路由</h2>
    )
}

const MyPage=()=>{
    const {user,setUser}=useUserContext()
    const history=useHistory()
    return <>
    <h2>我的页面</h2>
    <p>貂毛{user && user.username}</p>
    <button onClick={()=>{api.logout().then(()=>{setUser(null) 
     history.push('/auth/login')
    })}}>登出</button>
    </>
}
const MyRoute=(props)=>{
    const {user}=useUserContext()
    const location=useLocation()
   return user ?<Route {...props} />:
   <Redirect to={{pathname:'/auth/login',state:{from:location}}}/>
}

const AuthDemo = () => {
    return ( <UserContextProvider>
    <h1>自动智能路由</h1>
    <NavLink to='/auth/pub' style={(isActive)=>({
       textDecoration:isActive?'none':'underline' 
    })}>公开页面</NavLink>{' '}
    <NavLink to='/auth/login' style={(isActive)=>({
       textDecoration:isActive?'none':'underline' 
    })}>登录</NavLink>{' '}
    <NavLink to='/auth/my' style={(isActive)=>({
       textDecoration:isActive?'none':'underline' 
    })}>我的页面</NavLink>
    
        <Switch>
            <Route path='/auth/pub' component={Public}/>
            <Route path='/auth/login' component={Login}/>
            <MyRoute path='/auth/my' component={MyPage}/>
            <MyRoute path="/auth/my2" component={MyPage2} />
        </Switch>
    </UserContextProvider> );
}
 
export default AuthDemo;